module Requests where

import Util
import Data.Maybe
import Network.URI
import Network.HTTP
import Network.Stream
import Control.Exception
import System.IO.Error
import Numeric
import Data.Char

uri = "http://www.nozbe.com/api/actions/what-next/key-"

requestNextActions :: String -> IO (Maybe String)
requestNextActions api_key = simpleHTTP (buildRequest (uri ++ api_key)) >>= extractRspBody

extractRspBody (Right rsp)
    | null (rspBody rsp) = raise "Got nothing in response from nozbe.com.\n\
                                 \Please ensure that the api-key is correct."
    | otherwise = return $ Just (rspBody rsp)
extractRspBody _ = return Nothing

buildRequest = getRequest
    -- let uri = Data.Maybe.fromMaybe (error "Nothing from url parse") (parseURI u)
    -- in Request{rqURI=uri, rqMethod=GET, rqHeaders=[], rqBody=""}

api_prefix = "http://www.nozbe.com/api"

checkActions api_key ids = do
    let req = api_prefix
           ++ "/check/ids-" ++ join (escapeUrl ";") ids
           ++ "/key-" ++ api_key
    simpleHTTP $ buildRequest req


requestApiKey :: String -> String -> IO (Maybe String)
requestApiKey email password = do
    let req = api_prefix
           ++ "/login/email-" ++ escapeUrl email
           ++ "/password-" ++ escapeUrl password
    sendRequest req
    

createAction api_key proj contx name = do
    let req = api_prefix
           ++ "/newaction/name-" ++ (escapeUrl name)
           ++ "/project_id-" ++ proj
           ++ "/context_id-" ++ contx
           ++ "/time-15/next-true/key-" ++ api_key
    simpleHTTP (buildRequest req)

        
requestProjects :: String -> IO (Maybe String)

requestProjects api_key = do
    let req = api_prefix
           ++ "/projects/key-" ++ api_key
    (simpleHTTP (buildRequest req)) >>= extractRspBody


requestContexts :: String -> IO(Maybe String)

requestContexts api_key = do
    let req = api_prefix
           ++ "/contexts/key-" ++ api_key
    rsp <- (simpleHTTP (buildRequest req))
    extractRspBody rsp


sendRequest :: String -> IO (Maybe String)
sendRequest req = do
    resp <- simpleHTTP $ buildRequest req 
    case resp of
         Right rsp -> return $ Just $ rspBody rsp
         _ -> return $ Nothing
            


escapeUrl :: String -> String
escapeUrl = foldr escapeUrlChar ""

badUrlChars = [ ' ', '$', '&','+', ',', '/', ':', ';', '=', '?',
                '@', '"', '<', '>', '#', '%' ]


escapeUrlChar ch acu  = if ch `elem` badUrlChars then
                            '%' : (showHex (ord ch) acu)
                        else 
                            ch : acu

